import {userLogin, fakeMobileLogin, queryVerifyCode} from '../services/api';

export default {
  namespace: 'login',

  state: {
    status: undefined,
    submitting: false,
    verifyCode: '',
    serialNo: '',
    message: '',
  },

  effects: {
    * accountSubmit({payload}, {call, put}) {
      yield put({
        type: 'changeSubmitting',
        payload: true,
      });
      const response = yield call(userLogin, payload);
      yield put({
        type: 'loginHandle',
        payload: Object.assign(response, {type: payload.type}),
      });
      yield put({
        type: 'changeSubmitting',
        payload: false,
      });
    },
    * mobileSubmit(_, {call, put}) {
      yield put({
        type: 'changeSubmitting',
        payload: true,
      });
      const response = yield call(fakeMobileLogin);
      yield put({
        type: 'loginHandle',
        payload: response,
      });
      yield put({
        type: 'changeSubmitting',
        payload: false,
      });
    },
    * logout({payload, callback}, {put}) {
      yield put({
        type: 'logoutHandle',
        payload,
      });
      if (callback) {
        callback();
      }
    },
    * getVerifyCode(_, {call, put}) {
      const response = yield call(queryVerifyCode);
      yield put({
        type: 'verifyCodeHandle',
        payload: {
          image: `data:image/jpg;base64,${response.base64}`,
          serialNo: response.serialNo,
        },
      });
    },
  },

  reducers: {
    loginHandle(state, {payload}) {
      let status = '';
      if (payload.code !== '200') {
        status = 'error';
      }
      return {
        ...state,
        status,
        type: payload.type,
        message: payload.msg,
      };
    },
    changeSubmitting(state, {payload}) {
      return {
        ...state,
        submitting: payload,
      };
    },
    logoutHandle(state, {payload}) {
      return {
        ...state,
        status: payload.status,
      };
    },
    verifyCodeHandle(state, {payload}) {
      return {
        ...state,
        verifyCode: payload.image,
        serialNo: payload.serialNo,
      };
    },
  },
};
